<?php

	include('constantes.php');
	include('config.php');
	include('mysql.php');
	include('functions.php');

	// Log out their current Session
	//Start session
	session_start();
	//Unset the variables stored in session
	unset($_SESSION['SESS_MEMBER_ID']);

	$username = addslashes($_POST['iusername']);
	$password = addslashes($_POST['ipassword']);

	$ipasslen = strlen($password);
	$iuserlen = strlen($username);

	if ($iuserlen == 0 && $ipasslen == 0)	// Logging out
	{
		header("Location: ".$root_url."index.php?login=6");
		exit();
	}

	//connect to the database here
	$query = "SELECT password FROM account WHERE name = '".$username."';";
	$result = mysql_query($query);
	if(mysql_num_rows($result) < 1)	// No such user exists
	{
		// header("Location: ".$root_url."index.php?login=1");
		header("Location: ".$root_url."index.php?login=5");
		exit();
	}
	$userData = mysql_fetch_array($result, MYSQL_ASSOC);
	$hashed_password = $userData['password'];
	$passlen = strlen($hashed_password);

	$hash = hash('md5', $password);

	if ($passlen == 0 || $ipasslen == 0)	// No password set
	{
		// header("Location: ".$root_url."index.php?login=2");
		header("Location: ".$root_url."index.php?login=5");
		exit();
	}
	elseif($hash != $hashed_password)	// Incorrect password
	{
		// header("Location: ".$root_url."index.php?login=3");
		header("Location: ".$root_url."index.php?login=5");
		exit();
	}
	else
	{
		// Login successful - Validate the account also has GM access
		$AccountStatus = GetFieldByQuery("status", "SELECT status FROM account WHERE name = '".$username."'");
		if ($AccountStatus >= $MinAdminAccountStatus)
		{
			//Regenerate session ID to prevent session fixation attacks
			session_regenerate_id();

			$_SESSION['SESS_MEMBER_ID'] = $username;

			//Write session to disc
			session_write_close();

			//Start session
			session_start();

			header("Location: ".$root_url."index.php");
			exit();
		}
		else
		{
			// header("Location: ".$root_url."index.php?login=4");
			header("Location: ".$root_url."index.php?login=5");
			exit();
		}
	}

?>